package com.allenkerr.client.config;

import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import feign.Retryer;
import feign.codec.ErrorDecoder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author tw
 * @author 小柯
 * @date 2018/3/19
 */
@Configuration
public class FeignConfig {

  private static final int MILLIS_PER_SECOND = 1000;

  @Bean
  Request.Options options() {
    return new Request.Options(10 * MILLIS_PER_SECOND, 20 * MILLIS_PER_SECOND);
  }

  @Bean
  Retryer retryer() {
    return new Retryer.Default(100, 1000, 3);
  }

  @Bean
  Logger.Level level() {
    return Logger.Level.FULL;
  }

  @Bean
  Logger logger() {
    return new FeignLogger();
  }

  @Bean
  public RequestInterceptor requestInterceptor() {
    return new MdcRequestInterceptor();
  }

  /**
   * Default {@link ErrorDecoder}.
   *
   * @return ErrorDecoder
   */
  @Bean
  public ErrorDecoder errorDecoder() {
    return new ErrorDecoder.Default();
  }

  /**
   * Custom {@link ApacheHttpClientFactory}, enable compression.
   *
   * @return ApacheHttpClientFactory
   * @see HttpClientConfiguration.ApacheHttpClientConfiguration#apacheHttpClientFactory(HttpClientBuilder)
   */
  @Bean
  public ApacheHttpClientFactory apacheHttpClientFactory() {
    return () -> HttpClientBuilder.create().disableCookieManagement().useSystemProperties();
  }

}
